//
//  SmallDecisionsPkpContainerViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/8/6.
//

#import "SmallDecisionsPkpContainerViewController.h"
#import "SmallDecisionsPkpCell.h"
#import "AlignButton.h"

@interface SmallDecisionsPkpContainerViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *bottomContainerView;
@property (nonatomic, strong) AlignButton *addBtn;
@property (nonatomic, strong) AlignButton *lookBtn;
@property (nonatomic, strong) AlignButton *openBtn;
@property (nonatomic, strong) NSMutableArray *totalPkpList;
@property (nonatomic, strong) NSMutableArray *pkpList;
@property (nonatomic, strong) NSMutableArray *localPkpList;
@property (nonatomic, strong) UILabel *pkpTotalLabel;

@end

@implementation SmallDecisionsPkpContainerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setDefaultPkpData];
    [self generateRandomPkps];
    [self bottomContainerView];
    [self addBtn];
    [self lookBtn];
    [self openBtn];
}

- (void)setDefaultPkpData {
    [self.totalPkpList removeAllObjects];
    [self.localPkpList removeAllObjects];
    for(int i = 1,n = 14; i < n; i ++) {
        [self.totalPkpList addObject:[NSString stringWithFormat:@"fang_kuai_img_%d",i]];
        [self.totalPkpList addObject:[NSString stringWithFormat:@"hei_tao_img_%d",i]];
        [self.totalPkpList addObject:[NSString stringWithFormat:@"hong_tao_img_%d",i]];
        [self.totalPkpList addObject:[NSString stringWithFormat:@"mei_fang_img_%d",i]];
    }
    if(self.hasWang) {
        [self.totalPkpList addObjectsFromArray:@[@"da_wang_img",@"xiao_wang_img"]];
    }
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.totalPkpList];
    NSUInteger count = [tempArray count];
    for (NSInteger i = count - 1; i > 0; i--) {
        // 生成一个在0到i之间的随机数
        NSInteger n = arc4random_uniform((u_int32_t)(i + 1));
        [tempArray exchangeObjectAtIndex:i withObjectAtIndex:n];
    }
    [self.totalPkpList addObjectsFromArray:[tempArray copy]];
    [self.localPkpList addObjectsFromArray: [tempArray copy]];
}

- (void)generateRandomPkps {
    [self.pkpList removeAllObjects];
    while (self.pkpList.count < self.pkpTotal) {
        NSInteger randomNum = [self getRandomNumber];
        [self.pkpList addObject:self.totalPkpList[randomNum]];
        [self.totalPkpList removeObjectAtIndex:randomNum];
    }
    self.pkpTotalLabel.text = [NSString stringWithFormat:@"目前:%ld张",(long)self.pkpTotal];

    [self.collectionView reloadData];
}


// 生成指定范围内的随机数
- (NSInteger)getRandomNumber {
    // 所以我们需要调整范围
    return arc4random_uniform((uint32_t)(self.totalPkpList.count));
}

- (NSMutableArray *)totalPkpList {
    if(!_totalPkpList) {
        _totalPkpList = [[NSMutableArray alloc] init];
    }
    return _totalPkpList;
}

- (NSMutableArray *)pkpList {
    if(!_pkpList) {
        _pkpList = [[NSMutableArray alloc] init];
    }
    return _pkpList;
}

- (NSMutableArray *)localPkpList {
    if(!_localPkpList) {
        _localPkpList = [[NSMutableArray alloc] init];
    }
    return _localPkpList;
}


#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.pkpList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SmallDecisionsPkpCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SmallDecisionsPkpCellId" forIndexPath:indexPath];
    if(self.lookBtn.isSelected || self.addBtn.isSelected) {
        cell.imageView.image = [UIImage imageNamed:self.pkpList[indexPath.item]];
    } else {
        cell.imageView.image = [UIImage imageNamed:@"pk_img"];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SmallDecisionsPkpCell *cell = (SmallDecisionsPkpCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.imageView.image = [UIImage imageNamed:self.pkpList[indexPath.item]];
    weakSelf(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(!(weakself.lookBtn.isSelected || weakself.addBtn.isSelected)) {
            cell.imageView.image = [UIImage imageNamed:@"pk_img"];
        }
    });
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemW = (self.view.width - 10 * 5 ) / 3.0;
        CGFloat itemH = itemW * 1.4;
        layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
        layout.itemSize = CGSizeMake(itemW, itemH);
        layout.minimumInteritemSpacing = 10;
        layout.minimumLineSpacing = 10; // cell 间距
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.view addSubview:_collectionView];
        [_collectionView registerClass:[SmallDecisionsPkpCell class] forCellWithReuseIdentifier:@"SmallDecisionsPkpCellId"];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10);
            make.left.right.top.mas_offset(0);
            make.bottom.equalTo(self.bottomContainerView.mas_top);
        }];
    }
    
    return _collectionView;
}

- (UIView *)bottomContainerView {
    if(!_bottomContainerView) {
        _bottomContainerView = [[UIView alloc] init];
        [self.view addSubview:_bottomContainerView];
        
        [_bottomContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_offset(0);
        }];
    }
    return _bottomContainerView;
}

- (AlignButton *)addBtn {
    if(!_addBtn) {
        _addBtn = [AlignButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setTitle:@"增加一张" forState:UIControlStateNormal];
        [_addBtn setTitle:@"再来一局" forState:UIControlStateSelected];
        [_addBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [_addBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        _addBtn.alignType = AlignType_TextRight;
        _addBtn.padding = 15;
//        [_addBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        _addBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
        _addBtn.layer.cornerRadius = 25;
        _addBtn.layer.masksToBounds = YES;
        _addBtn.backgroundColor = SmallDecisionsSecondBgColor;
        [_addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomContainerView addSubview:_addBtn];
        [_addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(50);
            make.left.mas_equalTo(20);
            make.right.mas_equalTo(-20);
            make.top.mas_offset(30);
        }];
    }
    return _addBtn;
}

- (AlignButton *)lookBtn {
    if(!_lookBtn) {
        _lookBtn = [AlignButton buttonWithType:UIButtonTypeCustom];
        [_lookBtn setTitle:@"搂一眼" forState:UIControlStateNormal];
        [_lookBtn setTitle:@"盖住" forState:UIControlStateSelected];
        [_lookBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [_lookBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        _lookBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
        _lookBtn.layer.cornerRadius = 25;
        _lookBtn.layer.masksToBounds = YES;
        _lookBtn.backgroundColor = SmallDecisionsSecondBgColor;
        [_lookBtn addTarget:self action:@selector(lookBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomContainerView addSubview:_lookBtn];
        [_lookBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.left.mas_equalTo(self.addBtn);
            make.right.equalTo(self.addBtn.mas_centerX).offset(-5);
            make.top.equalTo(self.addBtn.mas_bottom).offset(20);
            make.bottom.mas_offset(-20 - self.view.safeAreaInsets.bottom);
        }];
    }
    return _lookBtn;
}

- (AlignButton *)openBtn {
    if(!_openBtn) {
        _openBtn = [AlignButton buttonWithType:UIButtonTypeCustom];
        [_openBtn setTitle:@"开牌" forState:UIControlStateNormal];
        [_openBtn setTitleColor:SmallDecisionsThemeFontColor forState:UIControlStateNormal];
        [_openBtn setTitleColor:[UIColor clearColor] forState:UIControlStateHighlighted];
        _openBtn.titleLabel.font = SmallDecisionsSetBoldFontSize(14);
        _openBtn.layer.cornerRadius = 25;
        _openBtn.layer.masksToBounds = YES;
        _openBtn.backgroundColor = SmallDecisionsThemeColor;
        [_openBtn addTarget:self action:@selector(openBtnAction) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomContainerView addSubview:_openBtn];
        [_openBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.top.width.mas_equalTo(self.lookBtn);
            make.left.equalTo(self.addBtn.mas_centerX).offset(5);
        }];
    }
    return _openBtn;
}



- (void)addBtnAction {
    if(self.addBtn.selected) { // 再来一局
        self.addBtn.selected = NO;
        self.addBtn.backgroundColor = SmallDecisionsSecondBgColor;
        self.lookBtn.hidden = NO;
        self.openBtn.hidden = NO;
        [self setDefaultPkpData];
        [self generateRandomPkps];
    } else {
        if(self.pkpList.count == self.localPkpList.count) {
            self.addBtn.enabled = NO;
        } else {
            NSInteger randomNum = [self getRandomNumber];
            [self.pkpList addObject:self.totalPkpList[randomNum]];
            [self.totalPkpList removeObjectAtIndex:randomNum];
            self.pkpTotalLabel.text = [NSString stringWithFormat:@"目前:%lu张",self.pkpList.count];
            [self.collectionView reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.collectionView scrollToBottom];
          });
        }
    }
}

- (void)lookBtnAction {
    self.lookBtn.selected = !self.lookBtn.isSelected;
    [self.collectionView reloadData];
}

- (void)openBtnAction {
    self.addBtn.selected = YES;
    self.addBtn.backgroundColor = SmallDecisionsThemeColor;
    [self.collectionView reloadData];
    self.lookBtn.hidden = YES;
    self.openBtn.hidden = YES;
}

- (UIView *)setCenterBarView {
    UIView *centerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 34)];
    centerView.backgroundColor = SmallDecisionsSecondBgColor;
    centerView.layer.cornerRadius = 17;
    centerView.layer.masksToBounds = YES;
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 34)];
    contentLabel.textColor = SmallDecisionsThemeFontColor;
    contentLabel.font = SmallDecisionsSetFontSize(16);
    contentLabel.textAlignment = 1;
    contentLabel.text = [NSString stringWithFormat:@"目前:%ld张",(long)self.pkpTotal];
    [centerView addSubview:contentLabel];
    self.pkpTotalLabel = contentLabel;
    return centerView;
}

@end
